package logic

import (
	"gin_study/_26_bluebell/dao/mysql"
	"gin_study/_26_bluebell/models"
	"gin_study/_26_bluebell/pkg/jwt"
	"gin_study/_26_bluebell/pkg/snowflake"
)

func SignUp(p *models.ParamSignUp) (err error) {
	// 判断用户是否存在
	if err = mysql.CheckUserExist(p.Username); err != nil {
		return
	}
	// 生成UUID
	userID := snowflake.GenID()
	// 构造user实例
	user := models.User{
		UserID:   userID,
		Username: p.Username,
		Password: p.Password,
	}
	// 保存进数据库
	return mysql.InsertUser(&user)
}

func Login(p *models.ParamLogin) (string, error) {
	// 判断用户是否存在
	user := &models.User{
		Username: p.Username,
		Password: p.Password,
	}
	// 验证用户
	err := mysql.Login(user)
	if err != nil {
		return "", err
	}
	return jwt.GenToken(user.UserID, user.Username)

}
